package com.pan.admin.module.channel.entity.vo;

import com.pan.admin.common.constant.module.StatisticEnum;
import com.pan.admin.common.utils.StatisticUtils;
import com.pan.admin.module.channel.entity.LoanChannelStatistic;
import lombok.Data;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 渠道统计返回前端值
 *
 * @author Pan
 */
@Data
public class LoanChannelStatisticVO {

    /**
     * 链接名称
     */
    private String name;
    /**
     * 总数
     */
    private List<Integer> total;
    /**
     * 创建时间
     */
    private List<String> createTime;

    public static List<LoanChannelStatisticVO> fill(List<LoanChannelStatistic> list, StatisticEnum statisticEnum) {
        List<LoanChannelStatisticVO> listVO = new ArrayList<>();
        Map<String, List<LoanChannelStatistic>> groupMap = list.stream().collect(Collectors.groupingBy(t -> t.getName()));
        //  获取填充时间
        List<String> fillTime = StatisticUtils.getFillTime(statisticEnum);

        Iterator<Map.Entry<String, List<LoanChannelStatistic>>> iterator = groupMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, List<LoanChannelStatistic>> next = iterator.next();
            String name = next.getKey();
            List<LoanChannelStatistic> value = next.getValue();

            LoanChannelStatisticVO statisticVO = new LoanChannelStatisticVO();
            statisticVO.setName(name);
            statisticVO.setTotal(new ArrayList<>());
            statisticVO.setCreateTime(new ArrayList<>());

            for (int i = 0; i < fillTime.size(); i++) {
                String time = fillTime.get(i);
                //  查找该时间段内是否存在数据
                Optional<LoanChannelStatistic> first = value.stream().filter(t -> t.getCreateTime().equals(time)).findFirst();
                if (first.isPresent()) {
                    //  存在则按顺序添加值\
                    statisticVO.getTotal().add(first.get().getTotal());
                } else {
                    statisticVO.getTotal().add(0);
                }
                statisticVO.getCreateTime().add(time);
            }
            listVO.add(statisticVO);
        }
        return listVO;
    }
}
